//
//  CSCryptionTool.m
//  CreateWithSuper
//
//  Created by chenjunbo on 2024/6/15.
//  Copyright © 2024 CS. All rights reserved.
//

#import "CSCryptionTool.h"
#import <CommonCrypto/CommonCryptor.h>

@implementation CSCryptionTool

size_t const kKeySizeValue = kCCKeySizeAES128;

+ (NSData * _Nonnull)encryptData:(NSData *)data k:(NSString *)k v:(NSString *)v {
    
    NSUInteger dataLength = data.length;
    char keyPtr[kKeySizeValue + 1];
    memset(keyPtr, 0, sizeof(keyPtr));
    [k getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    size_t encryptSize = dataLength + kCCBlockSizeAES128;
    void *encryptedBytes = malloc(encryptSize);
    size_t actualOutSize = 0;
    NSData *initVector = [v dataUsingEncoding:NSUTF8StringEncoding];
    
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                          kCCAlgorithmAES,
                                          kCCOptionPKCS7Padding,
                                          keyPtr,
                                          kKeySizeValue,
                                          initVector.bytes,
                                          data.bytes,
                                          dataLength,
                                          encryptedBytes,
                                          encryptSize,
                                          &actualOutSize);
    if (cryptStatus == kCCSuccess) {
        NSData *data = [NSData dataWithBytesNoCopy:encryptedBytes length:actualOutSize];
        return data;
    }
    free(encryptedBytes);
    return nil;
}

+ (NSData * _Nonnull)decryptData:(NSData *)data k:(NSString *)k v:(NSString *)v {
    NSUInteger dataLength = data.length;
    char keyPtr[kKeySizeValue + 1];
    memset(keyPtr, 0, sizeof(keyPtr));
    [k getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    size_t decryptSize = dataLength + kCCBlockSizeAES128;
    void *decryptedBytes = malloc(decryptSize);
    size_t actualOutSize = 0;
    NSData *initVector = [v dataUsingEncoding:NSUTF8StringEncoding];
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                          kCCAlgorithmAES,
                                          kCCOptionPKCS7Padding,
                                          keyPtr,
                                          kKeySizeValue,
                                          initVector.bytes,
                                          data.bytes,
                                          dataLength,
                                          decryptedBytes,
                                          decryptSize,
                                          &actualOutSize);
    if (cryptStatus == kCCSuccess)
    {
        NSData *data = [NSData dataWithBytesNoCopy:decryptedBytes length:actualOutSize];
        return data;
    }
    free(decryptedBytes);
    
    return nil;
}
@end
